package com.thinkfit.jy.fragment;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextClock;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.GsonUtils;
import com.common.lib.bean.SportInfoBean;
import com.common.lib.bean.SportRecordBean;
import com.common.lib.bean.UserBean;
import com.common.lib.bean.VideoBean;
import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.manager.DataManager;
import com.common.lib.mvp.contract.EmptyContract;
import com.common.lib.mvp.presenter.EmptyPresenter;
import com.common.lib.utils.BaseUtils;
import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.BrandInfoActivity;
import com.thinkfit.jy.activity.LoginActivity;
import com.thinkfit.jy.activity.UserProfileActivity;
import com.thinkfit.jy.activity.VersionActivity;
import com.thinkfit.jy.bean.WeatherBean;
import com.thinkfit.jy.contract.SportRecordContract;
import com.thinkfit.jy.presenter.SportRecordPresenter;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.utils.LogUtils;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.SystemUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 主页
 */
public class HomeJyFragment extends BaseFragment<SportRecordContract.Presenter> implements SportRecordContract.View {

    ImageView ivAutomticUpdatesSwitch;
    TextView tvWeather,tvSite,tvUserName,tvIntegral,tvUserDistance,tvUserTime,tvUserKcal;
    ImageView ivUserHead,ivUserCut,ivVipLevel,ivSex,ivDown;
    TextClock tvDate,tvWeek;
    LinearLayout llUesrInfo;

    RotateAnimation rotateAnimation;
    AnimatorSet animatorSetOut,animatorSetIn;

    boolean isUserInfo = false;

    public static HomeJyFragment getInstance(int index) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.BUNDLE_EXTRA, index);
//        bundle.putInt(Constants.BUNDLE_EXTRA_2, type);
        HomeJyFragment fragment = new HomeJyFragment();
        fragment.setArguments(bundle);
        return fragment;
    }



    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_jy;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initView(view);
        UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
        if(myInfo != null){
            getPresenter().getSportInfo();
        }
    }

    public void initView(View view){
        tvDate = view.findViewById(R.id.tv_date);
        tvWeek = view.findViewById(R.id.tv_week);
        tvWeather = view.findViewById(R.id.tv_weather);
        tvSite = view.findViewById(R.id.tv_site);
        ivUserHead = view.findViewById(R.id.iv_user_head);
        ivUserCut = view.findViewById(R.id.iv_user_cut);
        tvUserName = view.findViewById(R.id.tv_user_name);
        ivVipLevel = view.findViewById(R.id.iv_vip_level);
        ivSex = view.findViewById(R.id.iv_sex);
        tvIntegral = view.findViewById(R.id.tv_integral);
        ivDown = view.findViewById(R.id.iv_down);

        llUesrInfo = view.findViewById(R.id.ll_uesr_info);
        tvUserDistance = view.findViewById(R.id.tv_user_distance);
        tvUserTime = view.findViewById(R.id.tv_user_time);
        tvUserKcal = view.findViewById(R.id.tv_user_kcal);

        if(isUserInfo){
            llUesrInfo.setVisibility(View.VISIBLE);
        }else {
            llUesrInfo.setVisibility(View.GONE);
        }

        if(DataManager.Companion.getInstance().getLanguage() == 1){
            // 设置格式并指定 Locale
            tvWeek.setFormat24Hour(DateFormat.getBestDateTimePattern(Locale.ENGLISH, "EEEE"));
            tvWeek.setFormat12Hour(DateFormat.getBestDateTimePattern(Locale.ENGLISH,"EEEE"));
        }else {
            tvWeek.setFormat24Hour(DateFormat.getBestDateTimePattern(Locale.CHINESE, "EEEE"));
            tvWeek.setFormat12Hour(DateFormat.getBestDateTimePattern(Locale.CHINESE,"EEEE"));
        }


        ivUserHead.setOnClickListener(this);
        ivUserCut.setOnClickListener(this);
        ivDown.setOnClickListener(this);
        String ip = SystemUtils.getInstance().getIp(getContext());
        LogUtils.getInstance().l(LogUtils.HINT,"aaaaaaaaaaaaaaaaaaaaaaaaa  ip: "+ip);
//        getTq();//天气接口

    }

    String url = "http://apis.juhe.cn/simpleWeather/query?key=35526aa9795f9c44de2cc47fb46a0042&city=台北";

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build();

    public void getTq(){
        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String result = response.body().string();
                System.out.println("Response from " + url + ": " + result);
                try {
                    WeatherBean weatherBean = GsonUtils.fromJson(result, WeatherBean.class);
                    String info = weatherBean.getResult().getRealtime().getInfo();
                    String temperature = weatherBean.getResult().getRealtime().getTemperature();
                    tvWeather.setText(temperature+"℃");
//                    JSONObject jsonObject = new JSONObject.fromObject(result);
//                    int error_code = jsonObject.getInt("error_code");
//                    if (error_code == 0) {
//                        System.out.println("调用接口成功");
//
//                        JSONObject result1 = jsonObject.getJSONObject("result");
//                        JSONObject realtime = result1.getJSONObject("realtime");
//
//                        System.out.printf("城市：%s%n", result1.getString("city"));
//                        System.out.printf("天气：%s%n", realtime.getString("info"));
//                        System.out.printf("温度：%s%n", realtime.getString("temperature"));
//                        System.out.printf("湿度：%s%n", realtime.getString("humidity"));
//                        System.out.printf("风向：%s%n", realtime.getString("direct"));
//                        System.out.printf("风力：%s%n", realtime.getString("power"));
//                        System.out.printf("空气质量：%s%n", realtime.getString("aqi"));
//                    } else {
//                        System.out.println("调用接口失败：" + jsonObject.getString("reason"));
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    public void userInfoOutAnimation(){
        if(animatorSetOut == null){
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(llUesrInfo, "translationY", -100f, 0f);
            ObjectAnimator ivDoenAnimator = ObjectAnimator.ofFloat(ivDown, "translationY", -100f, 0f);
            objectAnimator.setDuration(500);
            ivDoenAnimator.setDuration(500);
            animatorSetOut = new AnimatorSet();
            animatorSetOut.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                    llUesrInfo.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    isUserInfo = true;
                    ivDown.startAnimation(rotateAnimation);
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animatorSetOut.playTogether(objectAnimator,ivDoenAnimator);//.after(rotationXAnimator)
        }
        animatorSetOut.start();

        int width = ivDown.getWidth();
        int height = ivDown.getHeight();
        if(rotateAnimation != null){
            rotateAnimation.cancel();
            rotateAnimation = null;
        }
        rotateAnimation = new RotateAnimation(0,180,(width/2f),(height/2f));
        rotateAnimation.setDuration(500);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isUserInfo = true;
                animatorSetOut.clone();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    public void userInfoInAnimation(){

        if(animatorSetIn == null){
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(llUesrInfo, "translationY", 0f, -100f);
            ObjectAnimator ivDoenAnimator = ObjectAnimator.ofFloat(ivDown, "translationY", 0f, -100f);
            objectAnimator.setDuration(500);
            ivDoenAnimator.setDuration(500);
            animatorSetIn = new AnimatorSet();
            animatorSetIn.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    isUserInfo = false;
//                    llUesrInfo.setVisibility(View.INVISIBLE);

                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            animatorSetIn.playTogether(objectAnimator,ivDoenAnimator);//.after(rotationXAnimator)
        }
        animatorSetIn.start();


    }

    public void rotateIn(){
        int width = ivDown.getWidth();
        int height = ivDown.getHeight();
        if(rotateAnimation != null){
            rotateAnimation.cancel();
            rotateAnimation = null;
        }
        rotateAnimation = new RotateAnimation(180,360,(width/2f),(height/2f));
        rotateAnimation.setDuration(500);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

//                animatorSetIn.clone();
                userInfoInAnimation();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ivDown.startAnimation(rotateAnimation);
    }


    @Override
    public void onResume() {
        super.onResume();
        UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
        if(myInfo != null){
            if(myInfo.getSex() == 1){
                ivSex.setImageResource(R.drawable.img_home_sex_boy);
            }else {
                ivSex.setImageResource(R.drawable.img_home_sex_girl);
            }
            tvUserName.setText(myInfo.getNickname());
            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
        }else {
//            tvUserName.setText(getString(R.string.app_main_user_name,getString(R.string.app_main_guest)));
            ivUserHead.setImageResource( R.drawable.app_not_login);
            tvUserName.setText("");
//            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
//            tvHint.setText(getString(R.string.app_main_login_please));
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("ddddddddddddddddddddddd   HomeJyFragment ");
//        DeviceTypeUtils.showBackButton(getContext().getApplicationContext());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ivDown.clearAnimation();
        if(animatorSetOut != null){
            animatorSetOut.clone();
            animatorSetOut = null;
        }if(animatorSetIn != null){
            animatorSetIn.clone();
            animatorSetIn = null;
        }
        if(rotateAnimation != null){
            rotateAnimation.cancel();
            rotateAnimation = null;
        }
    }

    @NonNull
    @Override
    protected SportRecordContract.Presenter onCreatePresenter() {
        return new SportRecordPresenter(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        if(map.containsKey(EventBusEvent.LOGIN_SUCCESS)){
            UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
            if(myInfo != null){
                if(myInfo.getSex() == 1){
                    ivSex.setImageResource(R.drawable.img_home_sex_boy);
                }else {
                    ivSex.setImageResource(R.drawable.img_home_sex_girl);
                }
                tvUserName.setText(myInfo.getNickname());
                BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
            }

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_user_head:
                UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();
                if(myInfo != null){
                    openActivity(UserProfileActivity.class);
                }else {
                    openActivity(LoginActivity.class);
                }
                break;
            case R.id.iv_down:
                if(isUserInfo){
                    rotateIn();
                }else {
                    userInfoOutAnimation();
                }
                break;
        }
    }

    @Override
    public void getSportInfoSuccess(SportInfoBean bean) {
        tvUserDistance.setText(bean.getDistance());
        tvUserTime.setText((bean.getAlltime()/60)+"");
        tvUserKcal.setText(bean.getKcal());
    }

    @Override
    public void getSportRecordSuccess(int page, ArrayList<SportRecordBean> list) {

    }

    @Override
    public void getSportRecordFailed() {

    }

    @Override
    public void getVideoCourseFailed() {

    }

    @Override
    public void getVideoCourseSuccess(int page, ArrayList<VideoBean> list) {

    }
}
